﻿using System;
using System.Collections.Generic;
using System.Net;
using System.ServiceModel.Web;

namespace Restful.Net.TestHost
{
    /// <summary>
    /// Dummy service implementation that handles the contact
    /// /addressbook/bjorn
    /// /addressbook/bjorn/contacts
    /// /addressbook/bjorn/contacts?groupname=friends
    /// /addressbook/bjorn/contacts/123
    /// </summary>
    public class ContactService
    {
        DomainObjectDatabase db = new DomainObjectDatabase();

        [RestMethod(Verb = HttpVerb.Post, UriTemplate = "", RequiresAuthentication = true)]
        public void PostContact(string ownerID, Contact contact)
        {
            db.CreateContact(ownerID, contact);
        }

        [RestMethod(Verb = HttpVerb.Put, UriTemplate = "/{contactid}", RequiresAuthentication = true)]
        public void PutContact(string ownerID, long contactID, Contact contact)
        {
            db.UpdateContact(ownerID, contactID, contact);
        }

        [RestMethod(Verb = HttpVerb.Get, UriTemplate = "/{contactid}", RequiresAuthentication = true)]
        public Contact GetContact(string ownerID, long contactID)
        {
            Contact contact = db.GetContact(ownerID, contactID);
            if (!string.IsNullOrWhiteSpace(RestContext.Current.Request.IfNoneMatch))
            {
                if (contact.GetETag().Equals(RestContext.Current.Request.IfNoneMatch))
                {
                    throw new WebFaultException(HttpStatusCode.NotModified);
                }
            }

            RestContext.Current.Response.ETag = contact.GetETag();
            return contact;
        }

        [RestMethod(Verb = HttpVerb.Delete, UriTemplate = "/{contactid}", RequiresAuthentication = true)]
        public void DeleteContact(string ownerID, long contactID)
        {
            db.DeleteContact(ownerID, contactID);
        }

        [RestMethod(Verb = HttpVerb.Get, UriTemplate = "", RequiresAuthentication = true)]
        public List<Contact> GetContacts(string ownerID)
        {
            IUser currentUser = RestContext.Current.CurrentUser;
            Console.WriteLine(currentUser.UserName);

            return db.GetAllContacts(ownerID);
        }

        [RestMethod(Verb = HttpVerb.Get, UriTemplate = "", RequiresAuthentication = true)]
        public List<Contact> GetContacts(string ownerID, string groupName)
        {
            return db.GetAllContacts(ownerID, groupName);
        }
    }
}
